package com.twu.biblioteca.controllers;


import com.twu.biblioteca.config.Message;
import com.twu.biblioteca.models.entities.Book;
import com.twu.biblioteca.models.services.Libary;
import com.twu.biblioteca.models.entities.Movie;
import com.twu.biblioteca.models.services.UserService;
import com.twu.biblioteca.views.LibaryView;
import com.twu.biblioteca.views.MenuView;
import com.twu.biblioteca.views.MessageView;

import java.util.List;

import static com.twu.biblioteca.config.LibaryResourceType.*;
import static com.twu.biblioteca.config.Message.*;

public class LibaryController {

    public static void listBooks() {
        LibaryView.listBooks((List<Book>) Libary.getAll(BOOK));
        MenuView.render();
    }

    public static void listMovies() {
        LibaryView.listMovies((List<Movie>) Libary.getAll(MOVIE));
        MenuView.render();
    }

    public static void checkoutBook() {
        if (UserService.currentUser != null) {
            doCheckoutBook();
        } else {
            MessageView.showNotice(Message.LOGIN_FIRST, true);
            UserController.login();
        }
    }

    public static void checkoutMovie() {
        if (UserService.currentUser != null) {
            doCheckoutMovie();
        } else {
            MessageView.showNotice(Message.LOGIN_FIRST, true);
            UserController.login();
        }
    }

    private static void doCheckoutMovie() {
        Movie movie = (Movie) Libary.findBy(MOVIE, LibaryView.getEnteredMovieName());
        if (Libary.checkout(movie)) {
            MessageView.showNotice(CHECK_MOVIE_SUCCESSFUL, true);
            MenuView.render();
        } else {
            MessageView.showNotice(CHECK_MOVIE_UNSUCCESSFUL, true);
            MenuView.render();
        }
    }

    public static void returnBook() {
        if (UserService.currentUser != null) {
            doReturnBook();
        } else {
            UserController.login();
        }
    }

    private static void doReturnBook() {
        Book book = (Book) Libary.findBy(BOOK, LibaryView.getEnteredBookName());
        if (Libary.returnBack(book)) {
            MessageView.showNotice(RETURN_BOOK_SUCCESSFUL, true);
            MenuView.render();
        } else {
            MessageView.showError(RETURN_BOOK_UNSUCCESSFUL);
            MenuView.render();
        }
    }

    private static void doCheckoutBook() {
        Book book = (Book) Libary.findBy(BOOK, LibaryView.getEnteredBookName());
        if (Libary.checkout(book)) {
            MessageView.showNotice(CHECK_BOOK_SUCCESSFUL, true);
            MenuView.render();
        } else {
            MessageView.showNotice(CHECK_BOOK_UNSUCCESSFUL, true);
            MenuView.render();
        }
    }

}
